<template>
  <div class="search-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <a-breadcrumb separator="/">
        <a-breadcrumb-item>
          <a href="/" target="_self">Home</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <span>{{route.query.keyword}}</span>
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <div class="search-content">
      <!-- 右侧产品展示 -->
      <div class="products-container">
        <div class="products-header">
          <div class="products-title">
            Search results
            <span class="products-count">({{ totalItems || 0 }} Styles)</span>
          </div>
          <div class="products-controls">
            <div class="sort-by">
              <span class="sort-label">Sort by</span>
              <a-dropdown>
                <a class="sort-selector" @click.prevent>
                  {{ sortOptions.find(option => option.value === sortValue)?.label }}
                  <down-outlined />
                </a>
                <template #overlay>
                  <a-menu @click="(e) => handleSort(e.key)">
                    <a-menu-item v-for="option in sortOptions" :key="option.value">
                      {{ option.label }}
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
            <div class="view-selector">
              <span class="view-label" v-if="!isSmallScreen">View</span>
              <a-radio-group v-model:value="gridView" button-style="solid" size="small">
                <a-radio-button value="2">2</a-radio-button>
                <a-radio-button value="4" v-if="!isXsScreen">4</a-radio-button>
                <a-radio-button value="6" v-if="!isSmallScreen">6</a-radio-button>
              </a-radio-group>
<!--              <span class="view-all-link" v-if="!isXsScreen">查看全部</span>-->
              <span class="page-indicator" v-if="!isXsScreen">
                <left-outlined @click="prevPage" :disabled="currentPage === 1" />
                <span>{{ currentPage }}</span> / <span>{{ Math.ceil(totalItems / params.page_size) }}</span>
                <right-outlined @click="nextPage" :disabled="currentPage === Math.ceil(totalItems / params.page_size)" />
              </span>
            </div>
          </div>
        </div>

        <!-- 骨架屏加载 -->
        <template v-if="loading">
          <div class="products-grid" :class="[`grid-${effectiveGridView}`]">
            <div v-for="i in 8" :key="i" class="product-card">
              <a-skeleton-image style="width:100%;margin-bottom:10px;" />
              <a-skeleton :paragraph="{ rows: 2 }" :title="true" active />
            </div>
          </div>
        </template>

        <!-- 空状态提示 -->
        <div v-else-if="productList.length === 0" class="empty-state">
          <div class="empty-state-icon">
            <img :src="SVG_ICONS.Empty" class="empty-icon-placeholder" alt="Product not found" />
          </div>
          <h3 class="empty-state-title">No related products found</h3>
          <p class="empty-state-description">Please try other search keywords</p>
          <a href="/" target="_self">
            <a-button type="primary" class="clear-filters-btn">Home</a-button>
          </a>
        </div>

        <!-- 商品列表 -->
        <div v-else class="products-grid" :class="[`grid-${effectiveGridView}`]">
          <div v-for="product in productList" :key="product.id" class="product-card" @click="viewProductDetails(product)">
            <div class="product-image-container">
              <img
                :src="product.images && product.images.length > 0 ? product.images[0] : ''"
                :alt="product.name"
                class="product-image"
              />
              <img
                :src="product.images && product.images.length > 1 ? product.images[1] : product.images[0]"
                :alt="product.name"
                class="product-hover-image"
              />
              <div class="product-actions">
                <a-button class="add-to-cart-btn" @click.stop="addCart(product)">Add +</a-button>
              </div>
            </div>
            <div class="product-info">
              <div class="product-name-container">
                <div class="product-name">{{ product.name }}</div>
                <HeartFilled v-if="product.is_favorited == 1" @click.stop="toggleFavorite(product)"/>
                <heart-outlined v-else class="wishlist-icon" :style="{ color: product.is_favorited ? '#ff4d4f' : '' }" @click.stop="toggleFavorite(product)"/>
              </div>
              <div class="product-price">
                {{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(product.min_price) }}
                <span v-if="product.discount_enabled === 1" class="original-price">
                   {{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(product.max_origin_price) }}
                </span>
                <span v-if="product.discount_enabled === 1" class="discount-tag">
                  {{ product.discount }}% OFF
                </span>
              </div>
              <div class="product-tags">
                <span v-if="isNewProduct(product.create_time)" class="tag new-arrival">New arrival</span>
                <span v-if="product.discount_enabled === 1" class="tag discount">
                  {{ product.discount }}% OFF
                </span>
              </div>
            </div>
          </div>
        </div>

        <div class="pagination-container" v-if="!loading && productList.length > 0">
          <a-pagination
            v-model:current="currentPage"
            :total="totalItems"
            :page-size="params.page_size"
            :show-total="(total: number) => `Total ${total} items`"
            @change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>

  <a-modal v-model:open="openDetail" width="1200px" title="Product Details" :footer="null">
    <ProductDetail.default v-if="openDetail && goodId" :goodId="goodId" @buy="handleBuy" />
  </a-modal>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, watch, getCurrentInstance} from 'vue';
import { DownOutlined, HeartOutlined, LeftOutlined, RightOutlined, HeartFilled } from '@ant-design/icons-vue';
import { useWindowSize } from '@vueuse/core';
import * as ProductDetail from '@/components/ProductDetail.vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { addFavorite } from '@/api/details';
import { delFavorite, getFavoriteList } from '@/api/goods';
import SVG_ICONS from '@/assets/SVG_ICONS';
import { Session } from '@/utils/storage';
import { getToken } from '@/utils/auth';
import {getClassifyIndex} from "@/api/classify.ts";
import { useCurrencyStore } from '@/store/currency'
import emitter from '@/utils/eventBus';
// 公共变量
const { proxy } = getCurrentInstance()
const currencyStore = useCurrencyStore()
const router = useRouter();
const route = useRoute();
const isLogin = ref(false);
const searchKeyword = ref('');

// 响应式相关
const { width } = useWindowSize();
const isSmallScreen = computed(() => width.value < 992);
const isXsScreen = computed(() => width.value < 768);

// 存储商品列表
const productList = ref<any[]>([]);
const totalItems = ref(0);

// 根据屏幕尺寸决定实际的网格布局
const gridView = ref('4');
const effectiveGridView = computed(() => {
  if (isXsScreen.value) return '2';
  if (isSmallScreen.value) return '3';
  return gridView.value;
});

// 当前页码
const currentPage = ref(1);

// 排序相关
const sortOptions = [
  {
    value: '0',
    label: 'Popular',
  },
  {
    value: '1',
    label: 'NEW',
  },
  {
    value: '2',
    label: 'Price low to high',
  },
  {
    value: '3',
    label: 'Price high to low',
  },
  {
    value: '4',
    label: 'Most Reviews',
  },
  {
    value: '5',
    label: 'Video',
  },
];

const sortValue = ref('0');

// 处理排序
const handleSort = (key: string) => {
  sortValue.value = key;
  params.value.sort_type = key;
  currentPage.value = 1;  // 重置为第一页
  params.value.page = 1;
  fetchSearchResults();  // 重新获取搜索结果
};

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page;
  params.value.page = page;

  // 滚动到页面顶部
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });

  // 获取新页的数据
  fetchSearchResults();
};

const prevPage = () => {
  if (currentPage.value > 1) {
    handlePageChange(currentPage.value - 1);
  }
};

const nextPage = () => {
  const totalPages = Math.ceil(totalItems.value / params.value.page_size);
  if (currentPage.value < totalPages) {
    handlePageChange(currentPage.value + 1);
  }
};

// ======================== 收藏商品 ==========================
// 获取收藏列表
const getFavoriteListApi = async () => {
  await getFavoriteList().then((res: any) => {
    if (res.code == 200) {
      Session.set('collectList', res.result)
      emitter.emit('getFavoriteApi');
      // 触发新收藏事件
      emitter.emit('newFavorite');
    } else {
      message.error(res.msg)
    }
  })
}

// 处理收藏功能
const toggleFavorite = async (product: any) => {
  if (isLogin.value) {
    // 登录状态
    if (product.is_favorited == 0) {
      await addFavorite({
        goods_id: product.id
      }).then((res: any) => {
        if (res.code === 200) {
          message.success('Successfully collected');
          getFavoriteListApi()
          // 更新商品收藏状态
          product.is_favorited = 1
        } else {
          product.is_favorited = 0
          message.error(res.data.msg);
        }
      })
    } else {
      await delFavorite({
        goods_id: product.id
      }).then((res: any) => {
        if (res.code === 200) {
          getFavoriteListApi()
          message.success('Cancel collection successfully');
          // 更新商品收藏状态
          product.is_favorited = 0
        } else {
          product.is_favorited = 1
          message.error(res.data.msg);
        }
      })
    }
  } else {
    // 未登录，提示登录
    message.warning('Please login first');
    router.push('/login');
  }
}

// 查看商品详情
const viewProductDetails = (product: any) => {
  if (product.url) {
    window.location.href = `/product/${product.url}.html`;
  }
}

// 加入购物车
const openDetail = ref(false);
const goodId = ref<string | null>(null);

const addCart = (product: any) => {
  // 防止穿透点击
  if (openDetail.value) {
    return;
  }
  // 打开购买弹窗
  openDetail.value = true;
  goodId.value = String(product.id);
}

interface BuyData {
  productId?: string | number;
  quantity?: number;
  [key: string]: any;
}

const handleBuy = (data?: BuyData) => {
  // message.success('The product has been successfully added to the cart, please go to the cart for settlement');
  openDetail.value = false;
};

// 添加新的方法判断是否为新品（例如30天内发布的商品）
const isNewProduct = (createTime: string) => {
  if (!createTime) return false;
  const productDate = new Date(createTime);
  const currentDate = new Date();
  const diffTime = currentDate.getTime() - productDate.getTime();
  const diffDays = diffTime / (1000 * 3600 * 24);
  return diffDays <= 30; // 30天内发布的视为新品
};

// 搜索参数
const params = ref({
  name: route.query.keyword,
  page_size: 24,
  page: 1,
});

// 新增 loading 状态
const loading = ref(false);

// 获取搜索结果
const fetchSearchResults = async () => {
  loading.value = true;
  try {
    searchKeyword.value = route.query.keyword as string || '';
    params.value.name = route.query.keyword;
    if (!searchKeyword.value) {
      loading.value = false;
      return;
    }
    const response = await getClassifyIndex(params.value);
    if (response.code === 200 && response.result) {
      productList.value = response.result.data || [];
      totalItems.value = response.result.total || 0;
    }
  } catch (error) {
    console.error('Search failed:', error);
    message.error('Search failed, please try again later');
  } finally {
    loading.value = false;
  }
};

// 监听路由变化，重新获取搜索结果
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword !== undefined) {
    // 重置分页和排序
    currentPage.value = 1;
    params.value.page = 1;
    fetchSearchResults();
  }
});

onMounted(() => {
  // 检测是否登录
  if (getToken()) {
    isLogin.value = true;
  }

  // 获取搜索结果
  fetchSearchResults();
});
</script>

<style scoped lang="scss">
.search-container {
  max-width: 1920px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb-container {
  margin-bottom: 20px;
}

.search-content {
  display: flex;
  position: relative;
}

/* 右侧产品区域样式 */
.products-container {
  flex: 1;
}

.products-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.products-title {
  font-size: 16px;
  font-weight: 700;
}

.products-count {
  color: #666;
  font-size: .75rem;
  display: inline-block;
  margin-left: .5rem;
}

.products-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
  flex-wrap: wrap;
}

.sort-by {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sort-label {
  font-size: 14px;
  text-decoration: underline;
}

.sort-selector {
  display: flex;
  align-items: center;
  gap: 5px;
}

.view-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.view-label {
  font-size: 14px;
}

.view-all-link {
  font-size: 14px;
  cursor: pointer;
  margin-left: 10px;
  text-decoration: underline;
}

.page-indicator {
  margin-left: 15px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.products-grid {
  display: grid;
  gap: 20px;
  margin-bottom: 30px;
}

.grid-2 {
  grid-template-columns: repeat(2, 1fr);
}

.grid-3 {
  grid-template-columns: repeat(3, 1fr);
}

.grid-4 {
  grid-template-columns: repeat(4, 1fr);
}

.grid-6 {
  grid-template-columns: repeat(6, 1fr);
}

.product-card {
  display: flex;
  flex-direction: column;
  position: relative;
  cursor: pointer;

  :deep(.ant-skeleton.ant-skeleton-element .ant-skeleton-image) {
    width: 100%;
    height: 540px;
  }
}

.product-name-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 5px;
}

.product-name {
  font-size: 14px;

  &:hover {
    cursor: pointer;
  }
}

.product-actions {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  gap: 10px;
  opacity: 1;
  visibility: visible;
}

.product-image-container {
  position: relative;
  overflow: hidden;
  margin-bottom: 10px;

  &:hover {
    cursor: pointer;
  }
}

.product-image {
  width: 100%;
  aspect-ratio: 3/4;
  object-fit: cover;
  transition: opacity 0.3s ease;
}

.product-hover-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-image-container:hover .product-image {
  opacity: 0;
}

.product-image-container:hover .product-hover-image {
  opacity: 1;
}

.wishlist-icon {
  background-color: white;
  padding: 8px;
  border-radius: 50%;
  font-size: 16px;
  cursor: pointer;
}

.add-to-cart-btn {
  background-color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 12px;
}

.product-info {
  padding: 5px 0;
}

.product-price {
  font-weight: 600;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-weight: normal;
  font-size: 0.9em;
}

.discount-tag {
  color: #ff4d4f;
  font-size: 0.9em;
  font-weight: bold;
}

.product-tags {
  display: flex;
  gap: 10px;
}

.tag {
  padding: .125rem .5rem;
  border-radius: .6875rem;
  font-weight: 400;
  font-size: .75rem;
  letter-spacing: .03125rem;
  background-color: #f2f2f2;
  display: inline-block;
  margin: .3125rem .375rem .3125rem 0;
}

.new-arrival {
  color: #000000;
}

.discount {
  color: #ff4d4f;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 自定义面包屑样式 */
:deep(.ant-breadcrumb) {
  margin: 0;
  color: #000000;
  font-size: 0.8rem;
  line-height: 1.5;
  letter-spacing: .5px;
  font-weight: 400;
}

:deep(.ant-breadcrumb a) {
  color: rgba(0, 0, 0, 0.9);
  transition: color 0.3s;
}

:deep(.ant-breadcrumb a:hover) {
  color: #000000;
  text-decoration: #000000;
  background-color: #FFFFFF;
}

:deep(.ant-breadcrumb-separator) {
  margin: 0 8px;
  color: rgba(0, 0, 0, 0.45);
}

:deep(.ant-breadcrumb > span:last-child) {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
}

/* 添加空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  border-radius: 8px;
  margin: 50px 0;
}

.empty-state-icon {
  margin-bottom: 20px;
}

.empty-icon-placeholder {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin: 0 auto;
  font-size: 40px;
  color: #bfbfbf;
}

.empty-state-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
  color: #333;
}

.empty-state-description {
  color: #666;
  margin-bottom: 20px;
  max-width: 400px;
}

// 响应式样式
@media screen and (max-width: 1200px) {
  .products-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .products-controls {
    width: 100%;
  }
}

@media screen and (max-width: 767px) {
  .products-controls {
    flex-direction: column;
    align-items: flex-start;
  }

  .sort-by, .view-selector {
    width: 100%;
  }
}
</style>
